package com.cswnode.Controller.interceptor;

import com.cswnode.Dao.UserMapper;
import com.cswnode.Entity.LoginTicket;
import com.cswnode.Entity.User;
import com.cswnode.Service.LoginService;
import com.cswnode.Service.UserService;
import com.cswnode.Util.Constant;
import com.cswnode.Util.CookieUtil;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author csw
 * @create 2020/9/18 13:28
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    //controller执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request,"ticket");
        if (ticket != null){
            LoginTicket loginTicket = loginService.findLoginTicket(ticket);
            if (loginTicket != null && loginTicket.getStatus() == Constant.LOGINTICKET_STATUS_ACTIVATION
                    && loginTicket.getExpired().after(new Date())) {
                User user = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user);
            }
        }
        return true;
    }
    //controller执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }
    //Template执行之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
